package com.ykht.proj.coupon.timer;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.ykht.proj.activity.Enum.AgreementStatusEnum;
import com.ykht.proj.activity.entity.VBrandAgreement;
import com.ykht.proj.activity.entity.VCard;
import com.ykht.proj.activity.entity.VInfo;
import com.ykht.proj.common.core.constant.CommonConstants;
import com.ykht.proj.common.core.constant.SecurityConstants;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.comsrv.constant.ComConstant;
import com.ykht.proj.comsrv.vo.SubscribeMsg;
import com.ykht.proj.comsrv.vo.SubscribeMsgCardExpire;
import com.ykht.proj.comsrv.vo.SubscribeMsgCouponExpire;
import com.ykht.proj.comsrv.vo.SubscribeMsgCouponTouTiaoExpire;
import com.ykht.proj.coupon.Enum.DelFlagEnum;
import com.ykht.proj.coupon.Enum.FxStatusEnum;
import com.ykht.proj.coupon.Enum.RecommendStatusEnum;
import com.ykht.proj.coupon.entity.*;
import com.ykht.proj.coupon.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@SuppressWarnings("all")
@Slf4j
@EnableScheduling
public class CouponTimer {

	@Resource
	private CnCouponService cnCouponService;
	@Resource
	private CnCouponLogService cnCouponLogService;
	@Resource
	private CnCompanyService cnCompanyService;
	@Resource
	private CnBrandService cnBrandService;
	@Resource
	private CnShopService cnShopService;
	@Resource
	private FxCmsInfoService fxCmsInfoService;
	/**
	 * 领取的优惠券过期
	 * 十分钟
	 */
	@Scheduled(cron = "0 */10 * * * ?")
	public void couponLogExpireTimer() {
		log.info("->定时任务：c端领取的优惠券过期 自动过期");
		CnCouponLog log = new CnCouponLog();
		log.setUpdateTime(LocalDateTime.now());
		log.setStatus(2);//状态0待使用，1已核销2已过期
		cnCouponLogService.update(log, (Wrappers.lambdaQuery(CnCouponLog.class)
				.eq(CnCouponLog::getStatus, 0)//状态0待使用，1已核销2已过期
				.lt(CnCouponLog::getExpireTime, LocalDateTime.now())));//到期时间小于现在

	}

	/**
	 * 优惠券过期 自动下架
	 * 夜里0点
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	@Transactional(rollbackFor = Exception.class)
	public void couponExpireTimer() {
		log.info("->定时任务：优惠券过期 自动下架");
		List<CnCoupon> mustExprieList = cnCouponService.list(Wrappers.lambdaQuery(CnCoupon.class)
				.eq(CnCoupon::getDateType, 1)//0领取后N天内有效1时间段
				.eq(CnCoupon::getStatus, 0)//目前上架
				.lt(CnCoupon::getEffectiveeEndTime, LocalDate.now()))
		.stream().map(o->{
			o.setStatus(1);
			return o;
		}).collect(Collectors.toList());//结束日期在今天之前的
		Map<Long, Long> map = mustExprieList.stream().collect(Collectors.groupingBy(CnCoupon::getBrandId, Collectors.counting()));

		List<CnBrand> brandList = new ArrayList<>();
		map.forEach((k,v)->{
			CnBrand brand = new CnBrand().selectById(k);
			int count = brand.getTyCouponCount()-v.intValue();
			brand.setTyCouponCount(count < 0 ? 0 : count);
			brandList.add(brand);
		});

		cnCouponService.updateBatchById(mustExprieList,100);
		cnBrandService.updateBatchById(brandList,100);

	}
	/**
	 * 优惠券过期 自动下架
	 * 夜里0点
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	@Transactional
	public void companyAndBrandAndShopExpireTimer() {
		log.info("->公司门店品牌定时任务（下架更新）");
		// 获取公司已上架的公司并且合同时间已到期
		List<CnCompany> companyList = cnCompanyService.list(Wrappers.lambdaQuery(CnCompany.class)
				.eq(CnCompany::getDelFlag, DelFlagEnum.usable.getValue())
				.eq(CnCompany::getDisplay, 0)
				.ge(CnCompany::getContractStartTime, LocalDateTime.now())
				.le(CnCompany::getContractEndTime, LocalDateTime.now()));
		if (null != companyList && companyList.size() > 0) {
			List<Long> companyIdList = companyList.stream().map(CnCompany::getId).collect(Collectors.toList());
		}
		// 获取品牌已上架的公司并且合同时间已到期
		List<CnBrand> brandList = cnBrandService.list(Wrappers.lambdaQuery(CnBrand.class)
				.eq(CnBrand::getDelFlag, DelFlagEnum.usable.getValue())
				.eq(CnBrand::getDisplay, 0)
				.ge(CnBrand::getContractStartTime, LocalDateTime.now())
				.le(CnBrand::getContractEndTime, LocalDateTime.now()));
		if (null != brandList && companyList.size() > 0) {
			List<Long> brandIdList = brandList.stream().map(CnBrand::getId).collect(Collectors.toList());
		}
		// 获取门店已上架的公司并且合同时间已到期
		List<CnShop> shopList = cnShopService.list(Wrappers.lambdaQuery(CnShop.class)
				.eq(CnShop::getDelFlag, DelFlagEnum.usable.getValue())
				.eq(CnShop::getDisplay, 0)
				.ge(CnShop::getContractStartTime, LocalDateTime.now())
				.le(CnShop::getContractEndTime, LocalDateTime.now()));
		if (null != shopList && shopList.size() > 0) {
			List<Long> shopIdList = shopList.stream().map(CnShop::getId).collect(Collectors.toList());
		}
	}

	@Resource
	private RocketMQTemplate rocketMQTemplate;


//	@Scheduled(cron = "0 */10 * * * ?")
////	@Scheduled(cron = "0 0 8 * * ?")
//	public void  vInfoExpire() {
//		log.info("->定时任务：优惠券 自动过期");
//		List<CnCouponLog> logs = new CnCouponLog().selectList(Wrappers.lambdaQuery(CnCouponLog.class).between(CnCouponLog::getExpireTime,LocalDateTime.now(),LocalDateTime.now().plusDays(3)));
//		List<Long> tempCouponIds = logs.stream().map(CnCouponLog::getCouponId).distinct().collect(Collectors.toList());
//		log.info("过期优惠券个数为：{}",tempCouponIds.size());
//		if (tempCouponIds.size() == 0) {
//			return;
//		}
//		List<CnCoupon> couponList = new CnCoupon().selectList(Wrappers.lambdaQuery(CnCoupon.class).in(CnCoupon::getId,tempCouponIds));
//		List<Long> couponIds = couponList.stream().map(CnCoupon::getId).collect(Collectors.toList());
//
//		logs = logs.stream().filter(o->couponIds.contains(o.getCouponId())).collect(Collectors.toList());
//		List<Long> perIds = logs.stream().map(CnCouponLog::getRecipientId).collect(Collectors.toList());
//
//		List<CnPerson> personList = new CnPerson().selectList(Wrappers.lambdaQuery(CnPerson.class).in(CnPerson::getId,perIds));
//
//		logs.forEach(o->{
//			CnCoupon coupon = couponList.stream().filter(oo->oo.getId().equals(o.getCouponId())).findFirst().get();
//			CnPerson person = personList.stream().filter(oo->oo.getId().equals(o.getRecipientId())).findFirst().get();
//			SubscribeMsgCouponExpire msg = null;
//			SubscribeMsgCouponTouTiaoExpire touTiaoExpire = null;
//			if (person != null) {
//				//0微信1百度2抖音
//				switch (person.getLoginType()){
//					case 0:
//						msg = new SubscribeMsgCouponExpire();
//						msg.setPersonId(person.getId());
//						msg.setPrice(coupon.getReductionMoney());
//						msg.setOpenId(person.getOpenId());
//						msg.setCouponName(coupon.getName());
//						msg.setCouponId(o.getCouponId());
//						msg.setContent("您的优惠券即将过期！");
//						msg.setEndTime(o.getExpireTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
//						msg.setType(ComConstant.SUBSCRIBE_MSG_COUPON_EXPIRE);
//						rocketMQTemplate.sendOneWay(ComConstant.SUBSCRIBE_MSG_TOPIC+":"+ComConstant.SUBSCRIBE_MSG_COUPON_EXPIRE,msg);
//						log.info("优惠券过期提醒：{}", JSONUtil.toJsonStr(msg));
//						break;
//					case 2:
//						touTiaoExpire = new SubscribeMsgCouponTouTiaoExpire();
//						touTiaoExpire.setPersonId(person.getId());
//						touTiaoExpire.setPrice(coupon.getReductionMoney());
//						touTiaoExpire.setOpenId(person.getOpenId());
//						touTiaoExpire.setCouponName(coupon.getName());
//						touTiaoExpire.setCouponId(o.getCouponId());
//						touTiaoExpire.setContent("您的优惠券即将过期！");
//						touTiaoExpire.setEndTime(o.getExpireTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
//						touTiaoExpire.setType(ComConstant.SUBSCRIBE_MSG_COUPON_EXPIRE_TOUTIAO);
//						rocketMQTemplate.sendOneWay(ComConstant.SUBSCRIBE_MSG_TOPIC+":"+ComConstant.SUBSCRIBE_MSG_COUPON_EXPIRE_TOUTIAO,touTiaoExpire);
//						log.info("优惠券过期提醒：{}", JSONUtil.toJsonStr(touTiaoExpire));
//						break;
//				}
//			}
//		});
//
//	}


	/**
	 * cms文章推荐 自动上线 和下线
	 * 夜里0点
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	@Transactional
	public void cmsRecommendExpireTimer() {
		log.info("->cms文章推荐 自动上线");
		UpdateWrapper<FxCmsInfo> workRecommend = new UpdateWrapper<>();
		workRecommend.lambda().eq(FxCmsInfo::getRecommendStatus, RecommendStatusEnum.TO_START.getValue())
				.lt(FxCmsInfo::getRecommendStartTime, LocalDateTime.now())
				.ge(FxCmsInfo::getRecommendEndTime, LocalDateTime.now())
				.set(FxCmsInfo::getRecommendStatus, RecommendStatusEnum.AT_WORK.getValue());
		fxCmsInfoService.update(workRecommend);
		log.info("->cms文章推荐 自动下线");
		UpdateWrapper<FxCmsInfo> overdueRecommend = new UpdateWrapper<>();
		overdueRecommend.lambda().lt(FxCmsInfo::getRecommendEndTime, LocalDateTime.now())
				.eq(FxCmsInfo::getRecommendStatus, RecommendStatusEnum.AT_WORK.getValue())
				.set(FxCmsInfo::getRecommendStatus, RecommendStatusEnum.BE_OVERDUE.getValue());
		fxCmsInfoService.update(overdueRecommend);
	}
	@Scheduled(cron = "0 */2 * * * ?")
	@Transactional
	public void autoCheckPass() {
		log.info("->三天销不审核 自动发放分金额");
		int day = -3;
		List<CnCouponLog> list = cnCouponLogService.list(Wrappers.lambdaQuery(CnCouponLog.class)
				.eq(CnCouponLog::getFxStatus, FxStatusEnum.UN_FEEDBACK.getValue())
				.gt(CnCouponLog::getVerificationTime,LocalDateTime.now().plusDays(day)));
		list.stream().limit(1).forEach(o->{
			o.setFeedbackStatus(0);
			o.setFeedbackContent("定时通过");
			o.setFeedbackTime(LocalDateTime.now());
			cnCouponLogService.updateFeedbackStatus(o);
		});
	}

}
